#include <stdio.h>
#include "screen.h"
#include "chinese.h" /* the messages defined */
#include "mario.h" /* the mario world definition */

/* main function */
int main(int argc, char* argv[]) {
	/* initialize the window */
	if (screen_init(WINDOW_WIDTH*TILE_SIZE, WINDOW_HEIGHT*TILE_SIZE)) {
		fprintf(stderr, "Screen initialization failed.\n");
		exit(1);
	}
	srand((int)time(0));
	world_init();
	/* center the world */
	window_moveto((WORLD_WIDTH-WINDOW_WIDTH)/2,(WORLD_HEIGHT-WINDOW_HEIGHT)/2);

	/* FPS control */
	u32 last_frame = 0;
	u32 frames = 0;
	u32 fps_timer = (u32)getticks();
	/* game loop: render and update */
	bool quit = false;
	while (!quit) {
		const u32 now = (u32)getticks();
		/* first clear screen with the color */
		screen_clear(32, 32, 32, 255);

		/* render the screen */
		int count = 0;
		int x, y;
		for (y = 0; y < WINDOW_HEIGHT; y++) {
			for (x = 0; x < WINDOW_WIDTH; x++) {
				window_render(x, y);
				count++;
			}
		}

		/* render text */
		char msg[80];
		/* flashing the text color. */
		settextcolor((frames / 6) % 6 == 0 ? 255 : 200, 128, 255);
		/* NOTICE: the Chinese text must be encoded with UTF8 */
		sprintf_s(msg, 80, MSG_HELLO);
		outtextxy(msg, TILE_SIZE, TILE_SIZE);

		/* calculate and show FPS */
		if (frames > SCREEN_FPS) {
			float fps = frames * 1000.0 / (getticks() - fps_timer);
			sprintf_s(msg, 80, "[%5.1f]", fps);
			settextcolor(128, 128, 128);
			outtextxy(msg, 20, (WINDOW_HEIGHT-2) * TILE_SIZE);
		}

		/* the above is rendering in memory,
		   now put them on the screen all in once.*/
		screen_update();
		frames++;

		/* handles events, update status now */
		while (event_poll()) {
			/* the close window event */
			if (event_type(QUIT)) {
				quit = true;
			}
			/* keyboard events */
			else if (event_type(KEYDOWN)) {
				switch (event_key()) {

					case KEY_ESCAPE:
						/* quit program */
						quit = true;
						break;
					case KEY_ENTER:
					case KEY_RETURN:
						/* restart the game */
						break;
				}
				//if (state.game_over) continue;
				switch (event_key()) {
					case KEY_UP:
					case KEY_w:
						/* rotate clockwise */
						window_move(0,-1);
						break;

					case KEY_DOWN:
					case KEY_s:
						/* down one step */
						window_move(0,1);
						break;

					case KEY_LEFT:
					case KEY_a:
						/* move left */
						window_move(-1,0);
						break;

					case KEY_RIGHT:
					case KEY_d:
						/* move right */
						window_move(1,0);
						break;
					case KEY_SPACE:
						/* fast down till the bottom */
						break;
				}
			}
		}

		/* if game over, skip below updates */
		//if (state.game_over) continue;

		if (getticks() - now < SCREEN_TICK_PER_FRAME) {
			//Wait remaining time
			SDL_Delay(SCREEN_TICK_PER_FRAME + now - getticks());
		}

	}
	return 0;
}

